<template>
  <!-- start 选择组织架构页面 -->
  <div class="department-container" v-loading.fullscreen.lock="loading">
    <div class="guide-model-box" v-if="nowGuideStep < 4"></div>
    <!-- start 主要内容 -->
    <div v-if="(depts && depts.length) || isSearchDepts" class="department-main">
      <div
        v-show="!collapse"
        class="department-left department-state"
      >
        <base-button ref="addbtnRef" v-if="providerEdit && !isProviderSign" type="primary" @event="addServiceMember(true)">
          添加外部服务商成员
        </base-button>
        <div
          ref="searchbtnRef"
          class="dept-search"
          :class="{
            'dept-search-border':
              (tenantType == 0 && hasStaffAuth) ||
              tenantType == 2 ||
              tenantType == 3
          }"
        >
          <el-input
            v-model="deptKeyword"
            placeholder="请输入服务商名称搜索"
            @input="debounce"
            @keyup.enter.native="debounce"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <!-- <div class="dept-add" @click="addDepartment(true)">
                +
              </div> -->
        </div>
        <div class="el-tabs__content" :style="{height: `calc(100% - ${treeHeight}px)`}">
          <!-- 服务商搜索框 -->
        
          <!-- start 左侧服务商列表 -->
          <div class="department-main-left">
            <!-- start 服务商列表树 -->
            <div class="department-tree-view">
              <div class="bc-dept">
                <base-tree-dept
                  expand
                  :data="depts"
                  :selected="[selectedDept]"
                  :show-checkbox="allowCheckDept"
                  @node-selected="initDeptUser"
                  @node-check="chooseDept"
                  :node-render="nodeRender"
                />
              </div>
            </div>
            <!-- end 服务商列表树 -->
          </div>
          <!-- end 左侧服务商列表 -->
        </div>
        <div
          ref="deleteBtnRef"
          v-if="hasStaffAuth"
          class="department-child-item dept-role-item dept-del-role-item"
          :class="{
            'department-role-selected': selectedRole.id == -1,
            'dept-del-role-item-expand': !collapse
          }"
          @click="chooseDelRole()"
        >
          <span>已删除账号 &nbsp;&nbsp;</span>
          <i class="iconfont icon-arrowright"></i>
        </div>
      </div>

      <!-- 组织架构伸缩 -->
      <div class="collapse">
        <div
          @click="btnCollapse('left')"
          v-show="collapseLeft"
          class="base-collapse-btn-left"
        >
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
        <div
          @click="btnCollapse('rigth')"
          v-show="collapseRight"
          class="base-collapse-btn-right"
        >
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
      </div>
      <!-- start 右侧已删除账号 -->
      <div
        v-if="activeName === 'role'"
        class="department-main-right department-main-right_bgFFF"
        v-loading.fullscreen.lock="roleLoading"
      >
        <!-- start 角色人员 -->
        <div class="department-user-block margin-top-0">
          <div class="dept-search-group">
            <el-input
              v-model="roleKeyword"
              placeholder="请输入成员名称搜索"
              style="width: 200px"
              @input="searchRole"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>

          <div class="department-user-table">
            <el-table
              v-table-style
              :data="rolePage.list"
              stripe
              @select="roleSelectionHandle"
              @select-all="roleSelectionHandle"
              :highlight-current-row="false"
              show-overflow-tooltip
              header-row-class-name="team-detail-table-header"
              ref="roleMultipleTable"
              class="team-table bbx-normal-list-box"
              :height="delTableContainerHeight"
            >
              <template slot="empty">
                <div v-show="!roleLoading" class="no-data-block"> <img class="service-no-icon" :src="salespersonImage" />暂无人员</div>
              </template>
              <el-table-column
                v-if="selectedRole.id != -1"
                type="selection"
                width="48"
                align="center"
                class-name="select-column"
              ></el-table-column>
              <el-table-column prop="displayName" label="姓名" width="180px">
                <div style="display: flex" slot-scope="scope">
                  <a
                    href="javascript:;"
                    @click="goUserDetail(scope.row.userId)"
                    class="view-detail-btn"
                  >
                    <template v-if="isOpenData">
                      <open-data type="userName" :openid="scope.row.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ scope.row.displayName }}
                    </template>
                  </a>
                  <span v-if="scope.row.isTeamLeader" class="super-admin-label">主管</span>
                  <span
                    v-if="scope.row.superAdmin == 2"
                    class="super-admin-label"
                  >主管理员</span
                  >
                  <div
                    style="display: flex"
                    v-if="scope.row.labelList && scope.row.labelList.length"
                  >
                    <span
                      v-for="item in scope.row.labelList"
                      :key="item.id"
                      class="super-admin-label super-admin-label-auto"
                    >{{ item.tagName }}</span
                    >
                  </div>
                </div>
              </el-table-column>
              <el-table-column
                prop="loginName"
                label="账号"
                v-if="tenantType == 1"
              />
              <template v-if="selectedRole.id == -1">
                <el-table-column label="删除时间" width="180px">
                  <template slot-scope="scope">{{
                    scope.row.deleteTime | fmt_datetime
                  }}</template>
                </el-table-column>
                <el-table-column
                  label="未完成事件"
                  width="120px"
                  v-if="!isBasicEditionHideEvent"
                >
                  <template v-if="scope.row.eventCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('event', scope.row.userId)
                      "
                    >{{ scope.row.eventCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column label="未完成工单" width="120px">
                  <template v-if="scope.row.taskCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('task', scope.row.userId)
                      "
                    >{{ scope.row.taskCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column label="负责客户数" width="120px">
                  <template v-if="scope.row.customerCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('customer', scope.row.userId)
                      "
                    >{{ scope.row.customerCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  label="个人备件库"
                  width="120px"
                  v-if="!isBasicEditionHidePart"
                >
                  <template v-if="scope.row.spareCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('stock', scope.row.userId)
                      "
                    >{{ scope.row.spareCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column label="待审批事项" width="120px">
                  <template v-if="scope.row.unApproveCount" slot-scope="scope">
                    <a
                      href
                      class="text-center"
                      @click.stop.prevent="
                        createTransTab('approve', scope.row.userId)
                      "
                    >{{ scope.row.unApproveCount }}</a
                    >
                  </template>
                </el-table-column>
                <el-table-column label="删除原因" width="180px">
                  <template slot-scope="scope">
                    <template v-if="scope.row.show">
                      手动删除
                    </template>
                    <template v-else>
                      应用可见范围删除
                    </template>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120px" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.show"
                      type="text"
                      @click="resume(scope.row.userId)"
                    >
                      恢复
                    </el-button>
                    <el-popover
                      v-else
                      placement="top-start"
                      width="200"
                      trigger="hover">
                      账号在应用可见范围之外，无法恢复
                      <el-button
                        slot="reference"
                        type="text"
                        class="disable-text"
                      >
                        恢复
                      </el-button>
                    </el-popover>
                    <el-button
                      v-if="scope.row.eventCount ||
                        scope.row.taskCount ||
                        scope.row.customerCount ||
                      scope.row.spareCount"
                      type="text"
                      class="transfer-btn"
                      @click="createTransTab('event', scope.row.userId)"
                    >去转交
                    </el-button>
                    <el-popover
                      v-else
                      placement="top-start"
                      width="150"
                      class="disable-popover"
                      trigger="hover">
                      没有要转交的事项
                      <el-button
                        slot="reference"
                        type="text"
                        class="disable-text"
                      >
                        去转交
                      </el-button>
                    </el-popover>
                  </template>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column label="服务商" show-overflow-tooltip>
                  <template slot-scope="scope">{{
                    scope.row.tagList &&
                      scope.row.tagList
                        .map(i => (i && i.tagName) || '')
                        .join('，')
                  }}</template>
                </el-table-column>
                <el-table-column prop="cellPhone" label="电话" />
                <el-table-column prop="enabled" label="状态">
                  <template slot-scope="scope">{{
                    scope.row.enabled == 1 ? '启用' : '停用'
                  }}</template>
                </el-table-column>
              </template>
            </el-table>

            <div class="table-footer bbx-normal-table-footer">
              <div class="list-info">
                共
                <span class="level-padding">{{ rolePage.total }}</span
                >记录， 已选中
                <span class="selectedCount">{{
                  roleMultipleSelection.length
                }}</span
                >条
              </div>
              <el-pagination
                class="customer-table-pagination"
                :pager-count="tenantType==0?5:7"
                background
                @current-change="roleJump"
                @size-change="roleHandleSizeChange"
                :page-sizes="defaultTableData.defaultPageSizes"
                :page-size="roleParams.pageSize"
                :current-page="roleParams.pageNum"
                layout="prev, pager, next, sizes, jumper"
                :total="rolePage.total"
              ></el-pagination>
            </div>
          </div>

         
        </div>
        <!-- end 角色人员 -->
      </div>
      <!-- end 右侧已删除账号 -->
      <!-- start 右侧子服务商 人员列表 -->
      <div v-else class="department-main-right">
        <!-- start 服务商 header -->
        <div ref="tableHeaderContainer" class="department-detail-header">
          <div
            class="department-detail-header-title department-detail-header-title-box"
            :style="{'margin-bottom':canRemove?'12px':'4px'}"
            v-if="Object.keys(selectedDept).length > 0"
          >
            <p class="title">
              {{canRemove ? deptInfo.serviceProviderName : '外部服务商'}}

              <button @click="openHelpDoc" v-if="!canRemove" type="button"
                      class="btn-text frame-header-btn frame-header-btn-bg"
                      title="帮助文档"
                      v-tooltip>
                <i class="iconfont icon-bangzhu"></i>
              </button>
            </p>
            <div class="dept-edit-del" id="v-dept-step-1">
              <div class="guide-disable-cover" v-if="nowGuideStep == 1"></div>
              <el-button type="plain-third" v-if="providerEdit&&selectedDept.serviceProviderTenantId"
                            @click="openDepartmentEditPanel(selectedDept.serviceProviderId || selectedDept.serviceProviderTenantId)">
                <i class="iconfont icon-edit-square"></i>编辑
              </el-button>
              <el-button type="plain-third" @click="delDepartment()"
                            v-if="providerDelete&&selectedDept.serviceProviderTenantId&&!isdele">
                <i class="iconfont icon-delete"></i>删除
              </el-button>
              <el-button v-if="providerView&&selectedDept.serviceProviderTenantId" size="small" type="primary" @click="addAdmin(selectedDept.serviceProviderTenantId)"
              >服务商主页</el-button
              >
             
            </div>
          </div>

          <el-row class="dept-info" v-if="canRemove">
            <el-col :span="8" class="form-view-col">
              联系电话：{{ deptInfo.linkPhone }}
            </el-col>
            <el-col :span="16" class="form-view-col">
              <el-tooltip placement="top">
                <div slot="content">
                  <template v-if="isOpenData && deptInfo.serviceProviderManager && deptInfo.serviceProviderManager.length">
                    <open-data v-for="item in deptInfo.serviceProviderManager" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ teamLeadersName }}
                  </template>
                </div>
                <p class="form-view-col-content">服务商主管：
                  <template v-if="isOpenData && deptInfo.serviceProviderManager && deptInfo.serviceProviderManager.length">
                    <open-data v-for="item in deptInfo.serviceProviderManager" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ teamLeadersName }}
                  </template>
                </p>
              </el-tooltip>
            </el-col>
          </el-row>
          <div v-else style="color:#8C8C8C">
            外部服务商模块，用于维护公司的服务商信息，包括服务商注册信息，授权信息等。
          </div>

          <!-- TODO: 面包屑列表 -->
        </div>
        <!-- end 服务商 header -->

        <el-tabs
          class="dept-tabs flex-1"
          v-model="activeName1"
          @tab-click="handleClick1"
        >
          <el-tab-pane label="成员信息" name="user">
            <!-- start 服务商人员 -->
            <div class="department-user-block">
              <div class="dept-search-group">
                <div class="dept-search-group-left">
                  <el-input
                    v-model="keyword"
                    placeholder="请输入成员信息搜索"
                    style="width: 200px;margin-right:12px"
                    @change="search"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>

                  <!-- 高级搜索 -->
                  <div class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
                    <i class="iconfont icon-filter"></i>
                    高级搜索
                  </div>

                  <base-button type="primary" @event="chooseUser()"
                               v-if="selectedDept.serviceProviderTenantId && isAuthStaff"
                  >添加成员</base-button
                  >
                  
                  <el-button type="plain-third"
                                v-if="canRemove && (providerDelete&&selectedDept.serviceProviderTenantId&&!isdele) && isAuthStaff"
                                @click="userDeleteConfirm('multiple')">
                    移除成员
                  </el-button>
                 
                  <base-button
                    type="primary"
                    @event="openCreateUserPanel()"
                    v-if="tenantType == 1 && isAuthStaff"
                  ><i class="iconfont icon-add2" style="margin-right:6px" ></i>新建账号</base-button
                  >
                  <base-button v-if="providerEdit&&!selectedDept.serviceProviderTenantId&&isAuthStaff" type="primary" @event="addServiceMember(false)">
                    移除至公司内部
                  </base-button>
                </div>
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link"
                  >更多操作 <i class="iconfont icon-caidanjiantou-zhankai"></i
                  ></span>
                  <el-dropdown-menu slot="dropdown">
                    
                    <template v-if="allowExportIN">
                      <el-dropdown-item v-if="isButtonDisplayed">
                        <div @click="exportAccount()">导出账号</div>
                      </el-dropdown-item>
                      <el-dropdown-item v-if="isButtonDisplayed">
                        <div @click="exportAccount('all')">导出全部</div>
                      </el-dropdown-item>
                      <el-dropdown-item v-if="isButtonDisplayed">
                        <div @click="exportFeed()">导出动态</div>
                      </el-dropdown-item>
                      <!-- <el-dropdown-item v-if="isButtonDisplayed">
                        <div @click="exportFeed('all')">导出全部动态</div>
                      </el-dropdown-item> -->
                    </template>
                    <el-dropdown-item v-if="isButtonDisplayed"> 
                      <div @click="openUpdateModal">批量更新</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="canRemove && isAuthStaff&&isButtonDisplayed"> 
                      <div @click="userDeleteConfirm('multiple')">批量删除</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isButtonDisplayed"> 
                      <div @click="actionMany('enable')">批量启用</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isButtonDisplayed"> 
                      <div @click="actionMany('unable')">批量停用</div>
                    </el-dropdown-item>

                    <!-- <el-dropdown-item v-if="productV2Gray">
                      <div @click="openWxDialog">维护微信</div>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <div @click="openTelDialog">维护电话</div>
                    </el-dropdown-item> -->
                  </el-dropdown-menu>
                </el-dropdown>
                <!-- <base-button type="primary" @event="searchModel.pageNum=1;search();trackEventHandler('search')" native-type="submit">搜索</base-button> -->
              </div>

              <div
                class="department-user-table"
              >
                <el-table
                  v-table-style
                  border
                  :data="userPage.list"
                  stripe
                  :height="tableContainerHeight"
                  @select="selectionHandle"
                  @select-all="selectionHandle"
                  @header-dragend="headerDragend"
                  :highlight-current-row="false"
                  header-row-class-name="team-detail-table-header"
                  ref="multipleTable"
                  class="team-table bbx-normal-list-box"
                >
                  <template slot="empty">
                    <div v-show="!loading" class="no-data-block">
                      <img class="service-no-icon" :src="salespersonImage" />
                      当前服务商暂无人员
                      <span
                        v-if="allowAddUser && selectedDept.serviceProviderTenantId"
                        class="active-btn"
                        @click="chooseUser()"
                      >添加成员</span
                      >
                    </div>
                  </template>
                  <el-table-column
                    type="selection"
                    width="48"
                    align="center"
                    class-name="select-column"
                  ></el-table-column>
                  <el-table-column
                    prop="displayName"
                    label="姓名"
                    :width="tableListForWidthStash.displayName.width"
                    show-overflow-tooltip
                  >
                    <div style="display: flex" slot-scope="scope">
                      <a
                        href="javascript:;"
                        @click="goUserDetail(scope.row.userId)"
                        class="view-detail-btn view-user-detail-btn"
                      >
                        <template v-if="isOpenData">
                          <open-data type="userName" :openid="scope.row.staffId"></open-data>
                        </template>
                        <template v-else>
                          {{ scope.row.displayName }}
                        </template>
                      </a>

                      <span
                        v-if="scope.row.isTeamLeader"
                        class="super-admin-label"
                      >主管</span
                      >
                      <span
                        v-if="scope.row.superAdmin == 2"
                        class="super-admin-label"
                      >主管理员</span
                      >
                      <div
                        style="display: flex"
                        v-if="scope.row.labelList && scope.row.labelList.length"
                      >
                        <span
                          v-for="item in scope.row.labelList"
                          :key="item.id"
                          class="super-admin-label super-admin-label-auto"
                        >{{ item.tagName }}</span
                        >
                      </div>
                    </div>
                  </el-table-column>
                  <el-table-column prop="loginName" label="账号" :width="tableListForWidthStash.loginName.width" />

                  <el-table-column prop="roleDepartment" label="所属部门" :width="tableListForWidthStash.roleDepartment.width" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{
                        scope.row.roles &&
                          scope.row.tagList.map(i => (i && i.tagName) || '').join('，')
                      }}
                    </template>
                  </el-table-column>

                  <el-table-column prop="role" label="角色" :width="tableListForWidthStash.role.width" show-overflow-tooltip>
                    <template slot-scope="scope">{{
                      scope.row.roles &&
                        scope.row.roles.map(i => (i && i.name) || '').join('，')
                    }}</template>
                  </el-table-column>

                  <el-table-column
                    prop="cellPhone"
                    label="电话"
                    :width="tableListForWidthStash.cellPhone.width"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="wechat"
                    label="微信"
                    :width="tableListForWidthStash.wechat.width"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="email"
                    label="邮箱"
                    :width="tableListForWidthStash.email.width"
                    show-overflow-tooltip
                  />
                 
                  <el-table-column prop="enabled" label="状态" :width="tableListForWidthStash.enabled.width">
                    <template slot-scope="scope">{{
                      scope.row.enabled == 1 ? '启用' : '停用'
                    }}</template>
                  </el-table-column>
                  <el-table-column prop="enabled" :width="tableListForWidthStash.createTime.width" label="创建时间">
                    <template slot-scope="scope">{{
                      scope.row.createTime | fmt_datetime
                    }}</template>
                  </el-table-column>
                  <template v-if="tenantType == 1 && isAuthStaff">
                    <!-- 多端操作按钮 -->
                    <el-table-column prop="workArea" label="操作" :width="tableListForWidthStash.workArea.width" fixed="right">
                      <template slot-scope="scope">
                        <el-button
                          :disabled="scope.row.pending"
                          type="text"
                          @click="openCreateUserPanel(scope.row)"
                          v-if="allowAccountEdit"
                        >编辑</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          v-if="scope.row.enabled == 1 && allowAccountStop"
                          type="text"
                          style="color: #e6a23c"
                          @click="toggleEnable(scope.row)"
                        >停用</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          v-else-if="allowAccountStop"
                          type="text"
                          @click="toggleEnable(scope.row)"
                        >启用</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          type="text"
                          style="color: #fb602c"
                          @click="deleteDeptUser(scope.row)"
                          v-if="allowAccountDelete"
                        >删除</el-button
                        >
                        <el-button
                          type="text"
                          @click="userResetPwdConfirm(scope.row.userId)"
                          v-if="allowAccountEdit"
                        >重置密码</el-button
                        >
                        <!-- <el-button
                          type="text"
                          style="color: #fb602c"
                          @click="openChangeDialog(scope.row)"
                          v-if="allowAccountEdit"
                        >资质管理</el-button
                        > -->
                      </template>
                    </el-table-column>
                  </template>
                  <template v-if="tenantType != 1">
                    <!-- 钉钉端操作按钮 -->
                    <el-table-column prop="workArea" label="操作" :width="tableListForWidthStash.workArea.width" fixed="right">
                      <template slot-scope="scope">
                        <el-button
                          :disabled="scope.row.pending"
                          type="text"
                          @click="openCreateUserPanel(scope.row)"
                          v-if="allowAccountEdit"
                        >编辑</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          v-if="scope.row.enabled == 1 && allowAccountStop"
                          type="text"
                          style="color: #e6a23c"
                          @click="toggleEnable(scope.row)"
                        >停用</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          v-else-if="allowAccountStop"
                          type="text"
                          @click="toggleEnable(scope.row)"
                        >启用</el-button
                        >
                        <el-button
                          :disabled="scope.row.pending"
                          type="text"
                          style="color: #fb602c"
                          @click="deleteDeptUser(scope.row)"
                          v-if="allowAccountDelete"
                        >删除</el-button
                        >
                        <!-- <el-button
                          type="text"
                          style="color: #fb602c"
                          v-if="allowAccountEdit"
                          @click="openChangeDialog(scope.row)"
                        >资质管理</el-button
                        > -->
                      </template>
                    </el-table-column>
                  </template>
                </el-table>

                <div class="table-footer bbx-normal-table-footer">
                  <div class="list-info">
                    共<span class="level-padding">{{ userPage.total }}</span
                    >记录
                  </div>
                  <el-pagination
                    class="customer-table-pagination"
                    background
                    :pager-count="tenantType==0?5:7"
                    @current-change="jump"
                    @size-change="handleSizeChange"
                    :page-sizes="defaultTableData.defaultPageSizes"
                    :page-size="params.pageSize"
                    :current-page="params.pageNum"
                    layout="prev, pager, next, sizes, jumper"
                    :total="userPage.total"
                  ></el-pagination>
                </div>
              </div>

              
            </div>
            <!-- end 服务商人员 -->
          </el-tab-pane>
          <el-tab-pane
            :label="!canRemove ? '服务商列表' : '子服务商列表'"
            name="dept"
          >
            <!-- start 下级服务商 -->
            <div class="department-child-block">
              <!-- start 下级服务商列表 -->
              <template v-if="subDeptExpand">
                <div class="dept-search-group">
                  <div class="dept-search-group-left">
                    <el-input
                      v-model="subDeptKeyword"
                      placeholder="请输入服务商名称搜索"
                      style="width: 200px;margin-right:12px"
                      @input="subDeptSearch"
                      @keyup.enter.native="subDeptSearch"
                    >
                      <i
                        slot="prefix"
                        class="el-input__icon el-icon-search"
                      ></i>
                    </el-input>
                    <base-button
                      type="primary"
                      @event="addDepartment()"
                      id="v-dept-step-3"
                      v-if="providerCreate"
                    ><i class="iconfont icon-add2" style="margin-right:6px" ></i>{{
                      !canRemove ? '新建服务商' : '新建子服务商'
                    }}</base-button
                    >
                  </div>
                  <span class="el-dropdown" @click="changeCol">
                    <span class="el-dropdown-link"
                    >选择列 <i class="iconfont icon-caidanjiantou-zhankai"></i
                    ></span>
                  </span>
                </div>
                <div
                  class="department-user-table"
                >
                  <el-table
                    v-table-style
                    border
                    class="team-table bbx-normal-list-box"
                    :data="subDepartmentsPage.list"
                    @header-dragend="headerDragend"
                    :height="tableContainerHeight"
                    stripe
                    header-row-class-name="team-detail-table-header"
                  >
                    <template slot="empty">
                      <div v-show="!loading" class="no-data-block"><img class="service-no-icon" :src="salespersonImage" />暂无{{!canRemove ? '服务商' : '子服务商'}}</div>
                    </template>
                    <el-table-column
                      v-for="(item, index) in TableColumn"
                      :key="index"
                      :prop="item.field"
                      :label="item.label"
                      :width="item.width || ''"
                      :fixed="item.fixLeft || false"
                      show-overflow-tooltip
                    >
                      <template v-if="item.show" slot-scope="scope">
                        <template
                          v-if="item.field == 'serviceProviderManager' && scope.row.serviceProviderManager">
                          <template v-if="isOpenData && scope.row.serviceProviderManager.length">
                            <open-data v-for="item in scope.row.serviceProviderManager" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                          </template>
                          <template v-else>
                            {{scope.row.serviceProviderManager.map(i => (i && i.displayName) || '').join('，')}}
                          </template>
                        </template>

                        <template
                          v-else-if="
                            item.field == 'address' && scope.row.province
                          "
                        >
                          {{ scope.row | fmt_address }}

                        </template>
                        <!-- 负责区域 -->
                        <template
                          v-else-if="
                            item.field == 'tagPlaceList'
                          "
                        >
                          <span style="margin-right:10px;" v-for="(item,index) in scope.row.tagPlaceList" :key="index">
                            {{ item | fmt_dist }}
                          </span>
                        </template>
                        
                        
                        <template v-else-if="item.field == 'label'">{{
                          scope.row.labelNames.join('，')
                        }}</template>
                        <template v-else-if="item.field == 'serviceProviderContact'">
                          <template v-if="isOpenData && Object.keys(scope.row.serviceProviderContact).length">
                            <open-data type="userName" :openid="scope.row.serviceProviderContact.staffId"></open-data>
                          </template>
                          <template v-else>
                            {{scope.row.serviceProviderContact.displayName}}
                          </template>
                        </template>
                        <template v-else-if="item.field === 'serviceProviderName'">
                          <div class="view-detail-btn" @click.stop="addAdmin(scope.row.id)">
                            {{scope.row.serviceProviderName}}
                          </div>
                        </template>
                        <template v-else>{{ scope.row[item.field] }}</template>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" :width="100" fixed="right">
                      <template slot-scope="scope">
                        <el-button
                          type="text"
                          v-if="providerEdit"
                          @click="openDepartmentEditPanel(scope.row.id)"
                        >编辑</el-button
                        >
                        <el-button
                          type="text"
                          style="color: #fb602c"
                          @click="delDepartment(scope.row.serviceProviderId)"
                          v-if="providerDelete"
                        >删除</el-button
                        >
                        
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="table-footer bbx-normal-table-footer">
                    <div class="list-info">
                      共<span class="level-padding">{{
                        subDepartmentsPage.total
                      }}</span
                      >记录
                    </div>
                    <el-pagination
                      class="customer-table-pagination"
                      :pager-count="tenantType==0?5:7"
                      background
                      @current-change="deptjump"
                      @size-change="depthandleSizeChange"
                      :page-sizes="defaultTableData.defaultPageSizes"
                      :page-size="subDepartmentsPage.pageSize"
                      :current-page="subDepartmentsPage.pageNum"
                      layout="prev, pager, next, sizes, jumper"
                      :total="subDepartmentsPage.total"
                    ></el-pagination>
                  </div>
                </div>
                
              </template>
              <!-- end 下级服务商列表 -->

              <!-- <div class="no-data-block" v-else>
            当前服务商不包含下级服务商 <span class="active-btn" @click="addDepartment">添加子服务商</span>
          </div>-->
            </div>
            <!-- end 下级服务商 -->
          </el-tab-pane>
        
          
        </el-tabs>
      </div>
      <!-- end 右侧子服务商 人员列表 -->
    </div>
    <!-- end 主要内容 -->

    <!-- start 没有服务商组织 -->
    <div v-if="!loading && !depts.length && !isSearchDepts" class="department-empty">
      <img :src="ontactEmptyImg" alt="">
      <p>您不在任何服务商中，请联系管理员分配</p>
    </div>
    <!-- end 没有服务商组织 -->

    <!-- start 新建人员 -->
    <base-modal
      :show.sync="userDialogVisible"
      class="add-dialog-container service_body" width="720px" @closed="userDialogVisible = false"
      :title="dialogUserTitle"
    >
      <create-user-panel
        ref="createUserPanel"
        @submit="userAdd"
        :user-row="userRow"
        :type-service-provider="1"
        key-from='serviceProvider'
      ></create-user-panel>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userDialogSubmit"
        >确 定</el-button
        >
      </span>
    </base-modal>
    <!-- end 新建人员 -->

    <!-- 导出动态的对话框 -->
    <el-dialog
      :visible.sync="exportDialogvisible"
      width="600px"
      @close="exportDialogClosed"
    >
      <template slot="title">
        <h3 v-if="isOpenData">
          导出动态
          <el-tooltip placement="top">
            <template slot="content">
              为保障系统导出功能中的账号信息完整性，请管理员在「账号权限-组织架构」中导入企业微信通讯录信息； <span class="export-link" @click="toExport">去导入</span>
            </template>
            <i class="iconfont icon-warning-circle-fill task-icon icon-color"></i>
          </el-tooltip>
        </h3>
        <h3 v-else>
          导出动态
        </h3>
      </template>
      <el-form label-position="top" ref="exportFormRef" >
        <el-form-item label="[可选]选择时间">
          <el-date-picker
            v-model="selectdatetime"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="动态类型" >
          <el-checkbox v-model="checkedAllTypes">工作状态</el-checkbox>
          <el-checkbox-group v-model="activeTypes" :disabled="checkedAllTypes">
            <el-checkbox :label="item.value" v-for="item in dynamicTypes" :key="item.value">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogClosed">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="exportData"
        >{{ pending ? '正在导出' : '导出' }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 重置密码的对话框 -->
    <el-dialog
      title="重置密码"
      :visible.sync="resetDialogvisible"
      width="400px"
      @close="resetDialogClosed"
      class="reset-dialog-form-dialog"
    >
      <el-form
        ref="restFormRef"
        
        label-position="top"
        class="reset-dialog-form"
        :rules="changePassWordFormRules"
        :model="resetForm"
      >
        <label>确定将该成员的密码重置吗？</label>
        <el-form-item label="重置后密码：" required prop="pwd">
          <input type="password" style="position: fixed; left: -9999px" />
          <el-input
            placeholder="请输入密码"
            v-model="resetForm.pwd"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetDialogClosed">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="resetUserPwd"
        >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 新建部门 -->
    <base-modal :title="dialogTitle" :show.sync="deptDialogVisible" class="add-dialog-container service_body" width="700px" @closed="deptDialogVisible = false">
      <team-edit-view ref="team" :id="deptEditId||0"></team-edit-view>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </base-modal>
    <!-- start 导入服务微信 -->
    <!-- start 选择角色-->
    <el-dialog
      :visible.sync="addUserForm.isChangeRole"
      :show-close="true"
      title="修改角色"
    >
      <el-form
        :model="addUserForm"
        ref="form"
        
        label-position="top"
        class="demo-ruleForm"
      >
        <el-form-item >
          <p>从公司组织架构添加成员进入外部服务商时，需重新选择用户角色</p>
        </el-form-item>
     
        <el-form-item label="角色" prop="label">
          <el-select v-model="addUserForm.roleId" placeholder="请选择">
            <el-option
              v-for="item in addUserForm.roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeRoleSubmit"
        >确 定</el-button
        >
      </span>
    </el-dialog>
    <!--end 选择角色-->

    <!--start 选择列-->
    <biz-select-column
      ref="advanced"
      mode="ServiceProvider"
      :sotrage-key="'serviceProvider_select_colum'"
      @save="saveColumnStatus"
    />

    <!--end 选择列-->

    <base-import
      title="维护服务微信"
      ref="serviceWxModal"
      :is-import-now="true"
      :action="importWechat"
    >
      <div slot="tip">
        <div class="base-import-warn">
          请先下载<a
            :href="
              `${importWechatTem}?tagId=${selectedDept.id}`
            "
          >导入模版 </a
          >，填写完成后再上传导入。<br />
          微信号仅用于客户联系服务人员；<br />
          如果微信号未填写，客户将无法获取服务人员微信号；<br />
          此数据为非必填项。<br />
        </div>
      </div>
    </base-import>
    <!-- end 导入服务微信 -->

    <!-- start 导入服务电话 -->
    <base-import
      title="维护服务电话"
      ref="serviceTelModal"
      :is-import-now="true"
      :action="importCellPhone"
    >
      <div slot="tip">
        <div class="base-import-warn">
          请先下载<a
            :href="`${importCellPhoneTem}?tagId=${selectedDept.id}`"
          >导入模版 </a
          >，填写完成后再上传导入。<br />
          这里维护服务电话仅用于给客户发送预约短信时显示服务人员电话；<br />
          如果没有维护服务人员电话将会发送短信设置中统一服务电话；<br />
          此数据为非必填项。 <br />
          <br />
          短信示例<br />
          <br />
          【售后宝】尊敬的客户您好，{公司名称}{计划时间}安排{服务人员姓名}{服务电话}为您提供服务，请安排好您的时间，{客服电话}，谢谢
        </div>
      </div>
    </base-import>
    <!-- end 导入服务电话 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      :storage-key="advancedColumnNumStorageKey"
      @reset="resetParams"
      @search="initialize()"
      @changeWidth="setAdvanceSearchColumn"
      @getColumnNum="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="fields">
      </base-search-panel>
    </base-search-drawer>

    <!-- start 新建人员 -->
    <base-modal
      class="add-dialog-container service_body"
      width="700px"
      :title="addMemberFlag ? '添加外部服务商成员' : '移除至公司内部'"
      :show.sync="addMemberVisible"
      @closed="addMemberVisible = false"
    >
      <service-add-member :is-show="addMemberFlag" @submit="succSubmit" ref="serviceAddForm"></service-add-member>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addMemberVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMemberSubmit">
          确 定
        </el-button>
      </span>
    </base-modal>
    <!-- end 新建人员 -->


    <!-- start 批量更新 -->
    <base-import
      title="批量更新"
      ref="updateModal"
      :is-import-now="false"
      @success="updateSuccess"
      :action="updateAccount"
    >
      <div slot="tip">
        <div class="base-import-warn">
          请先下载<a @click="downloadTem" href="javascript:;">导入模版 </a
          >，填写完成后再上传导入。<br />
        </div>
      </div>
    </base-import>
    <!-- end 批量更新 -->
    <div ref="bridge" style="display: none;"></div>

    <change-dialog ref="changeDialog" :row='currentRow'></change-dialog>
  </div>
  <!-- end 选择组织架构页面 -->
</template>

<script>
// pageDes 服务商管理-服务商管理
/* api */
import * as serviceProviderApi from '@src/api/serviceProviderApi';
import { checkButtonDisplayed } from '@src/util/dom';

import {
  getRoleUser,
  getDelUser,
  resetPwdUpdateAdmin,
  getDepartmentUserCount,
  getBuyAndUseUserNum,
  createAndAddDepartmentUser,
  getBaseLabelList
} from '@src/api/DepartmentApi';
import * as TeamApi from '@src/api/TeamApi';

import { getAdvancedFields } from './fields';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'

// const
import { RoleType, TagType } from '@src/modules/dept/AdvancedType.ts';

import md5 from 'js-md5';
import { storageGet, storageSet } from '@src/util/storageV2.js'; /* enum */
/* components */
import CreateUserPanel from '@src/modules/dept/component/CreateUserPanel.vue';
import {
  isBasicEditionControl,
  isBasicEditionHideEvent,
  isBasicEditionHidePart
} from '@shb-lib/version';
import TeamEditView from '@src/modules/serviceProvider/component/CreateTeamPanel.vue';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
// 添加外部服务商成员
import ServiceAddMember from '@src/modules/serviceProvider/component/ServiceAddMember.vue';

// img
import { getOssUrl } from '@src/util/assets'
const ontactEmpty = getOssUrl('/no_data.png')
/* export & import */
import { importWechat, importWechatTem, importCellPhone, importCellPhoneTem, updateAccount } from '@src/api/Import';
import ChangeDialog from '@src/modules/serviceProvider/component/ChangeDialog.vue';

/* utils */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import _ from 'lodash';
import { safeNewDate } from '@src/util/time';
import http from '@src/util/http';
import Page from '@model/Page';
import platform from '@src/platform';
import Platform, { isOpenData, openAccurateTab } from '@src/util/platform.ts';
import tourGuide from '@src/mixins/tourGuide';
import { formatDate, getTimestamp, objectToUrlParams, objectDateToTimestamp } from 'pub-bbx-utils';

import { ValidatePassWordReg } from '@src/model/const/Reg'
import { PASS_WORD_MESSAGE } from '@src/model/const/Alert'
import { defaultTableData } from '@src/util/table'

let export_state;
const pageSizeStorageKey = 'serviceProvider_list_pageSize'

let validatePass = (rule, value, callback) => {
  
  if (!value) {
    callback(new Error('请输入密码'));
  } else {
    
    if (value) {
      if (ValidatePassWordReg.test(value)) {
        callback();
      } else {
        callback(new Error(PASS_WORD_MESSAGE));
      }
    }
    
    callback();
  }
};
const salespersonImage = getOssUrl('/salesperson.png')
export default {
  name: 'department-view',
  inject: ['initData'],
  mixins: [tourGuide],
  data() {
    return {
      defaultTableData,
      salespersonImage,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      userDialogVisible: false,
      deptDialogVisible: false,
      showParent: false,
      subDeptExpand: true,
      subDeptKeyword: '',
      isAllotByDept: false,
      nowGuideStep: 5,
      collapse: false,
      collapseLeft: true,
      collapseRight: false,
      deptKeyword: '',
      activeName: 'tag',
      activeName1: 'user',
      roles: [],
      selectedRole: {},
      keyword: '',
      roleKeyword: '',
      roleLoading: true,
      pending: false,
      roleMultipleSelection: [],
      roleParams: {},
      exportDialogvisible: false,
      resetDialogvisible: false,
      resetForm: {
        userId: '',
        pwd: ''
      },

      selectdatetime: null,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 360);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      deptInfo: {},
      userRow: '',
      allowCheckDept: false,
      depts: [],
      deptUserCount: {}, // 服务商人员数量统计
      isSeeAllOrg: false, // 是否开始降低组织架构人员可见性开关
      loading: true,
      multipleSelection: [],
      params: {},
      selectedDept: {}, // 选中的服务商
      userPage: new Page(), // 用户列表
      rolePage: new Page(),
      subDepartmentsPage: new Page(),
      userCount: 0, // 已开通账号数量
      accountNum: 0, // 账号总数量
      surplusNum: 0, // 剩余
      addUserForm: {
        userIds: [],
        tagIds: [],
      },
      deptEditId: '',
      isChangeColumn: false,
      columnsList: [],
      quanxian: {},
      isDelete:[],
      currentTabId: '',
      // 高级搜索
      visible: false,
      columnNum: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.RoleListAdvancedColumnNum,
      rolesList: [],
      baseLaberlList: [],
      addMemberVisible: false,
      addMemberFlag: true,
      isSearchDepts: false, // 是否进行了搜索
      importWechat,
      importWechatTem,
      importCellPhone,
      importCellPhoneTem,
      updateAccount,

      // 存储列表宽度缓存
      tableListForWidthStash:{
        displayName:{width:'180px'},
        loginName:{width:'120px'},
        roleDepartment:{width:'120px'},
        role:{width:'120px'},
        cellPhone:{width:'120px'},
        wechat:{width:'120px'},
        email:{width:'120px'},
        enabled:{width:'120px'},
        workArea:{width:'215px'},
        createTime:{width:'160px'}
      },
      // 列表缓存标识
      tableStashKey:'serviceProviderRoleList',
      // 动态类型
      dynamicTypes:[
        {value:0, name:'工单备注'},
        {value:1, name:'工单日志'},
        {value:2, name:'工单位置'}
      ],
      activeTypes:[],
      checkedAllTypes:true,
      currentRow: {},
      changePassWordFormRules: {
        pwd: [
          {
            required: true,
            validator: validatePass,
            trigger: ['blur', 'change']
          },
          { min: 8, message: '最小长度需为 8 位', trigger: 'blur' }
        ],
      },
      tableContainerHeight:'440px',
      delTableContainerHeight:'440px',
      treeHeight: 154, // 默认服务商树的高度（按添加按钮和删除按钮默认显示）
    };
  },
  computed: {
    TableColumn(){
      return this.columnsList.filter(item=>item.show)
    },
    isdele(){
      return this.isDelete.some(x=>x === this.selectedDept.id)
    },
    dialogTitle(){
      return this.deptEditId ? `修改${!this.canRemove ? '' : '子'}服务商` : `新建${!this.canRemove ? '' : '子'}服务商`
    },
    dialogUserTitle(){
      return this.userRow ? '修改账号' : '新建账号'
    },
    corpId() {
      return this.initData.corpId || '';
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return this.initData.tenantType;
    },
    authorities() {
      return this.initData.authorities || {};
    },
    allowAddUser() {
      return (
        this.authorities.AUTH_STAFF == 3
        && this.authorities.AUTH_ROLE == 3
        && this.authorities.AUTH_TAG == 3
      );
    },
    providerCreate() {
      return 'PROVIDER_CREATE' in this.authorities;
    }, // 新建服务商
    providerDelete() {
      return 'PROVIDER_DELETE' in this.authorities;
    }, // 删除服务商
    providerEdit() {
      return 'PROVIDER_EDIT' in this.authorities;
    }, // 编辑服务商
    providerView() {
      return 'PROVIDER_VIEW' in this.authorities;
    }, // 查看服务商
    // 查看组织架构权限对应之前的团队权限
    hasTagAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_TAG' in this.authorities;
    },
    // 账号权限
    hasStaffAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_STAFF' in this.authorities;
    },
    // 角色权限
    hasRoleAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_ROLE' in this.authorities;
    },
    // 是否账号管理权限
    isAuthStaff(){
      return 'AUTH_STAFF' in this.authorities;
    },
    isAllowCreate() {
      return this.authorities?.PROVIDER_CREATE
    },
    isAllowEdit() {
      return this.authorities?.PROVIDER_EDIT
    },
    isAllowDelete() {
      return this.authorities?.PROVIDER_DELETE
    },
    allowAccountEdit() {
      return this.authorities?.AUTH_STAFF
    },
    allowAccountStop() {
      return this.authorities?.ACCOUNT_STOP
    },
    allowAccountDelete() {
      return this.authorities?.ACCOUNT_DELETE
    },
    allowAccountImport() {
      return this.authorities?.ACCOUNT_IMPORT && this.allowAccountCreate
    },
    teamLeadersName() {
      return (
        this.deptInfo.serviceProviderManager
        && this.deptInfo.serviceProviderManager
          .map(i => (i && i.displayName) || '')
          .join('，')
      );
    },

    canRemove() {
      // 主服务商下面成员不能移除
      return this.selectedDept.parentId;
    },
    // 是否在钉钉环境
    isDingTalk() {
      return Platform.isDingTalk();
    },
    productV2Gray() {
      return this.initData.openSuperCodePro;
    },
    isBasicEditionControl() {
      return isBasicEditionControl();
    },
    // 基础版隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
    // 基础版隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart();
    },
    // 高级搜索字段
    fields() {
      let f = {};
      return getAdvancedFields(this)
        .map(field => {
          f = _.cloneDeep(field);
          let formType = f.formType;

          if (f.displayName === '所属部门') {
            formType = 'tags';
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
          })
        })
        .sort((a, b) => a.orderId - b.orderId)
        .filter( x => this.canRemove ? x.fieldName !== 'tags' : x );
    },
    ontactEmptyImg(){
      return ontactEmpty;
    },
    // 当前账号是否存在服务商部门
    isProviderSign(){
      return sessionStorage.getItem('isProviderSign') == 1;
    },
    /* 导入导出 */
    allowExportIN() {
      return true
      // return AuthUtil.hasAuth(this.authorities, 'EXPORT_IN');
    },
  },
  watch:{
    activeName1(newVal, oldVal){
      this.$nextTick(()=>{
        this.buildColumn()
      })
    },
    checkedAllTypes(newVal){
      if(newVal)this.activeTypes = []
    }
  },
  async created() {
    await this.getCol();
  },
  mounted() {
    this.currentTabId = window.frameElement?.dataset?.id;
    // isAllotByDept对应钉钉端是否按照钉钉通讯录选人 如果钉钉端之前勾选了按服务团队派单isAllotByDept为false,
    // 去掉引导页面
    if (this.tenantType == 0) {
      // 钉钉端
      this.isAllotByDept = !this.initData.allotByTag;
    }
    // 读取列表的分页缓存数据
    let pageSizeStash = storageGet(pageSizeStorageKey) || '';
    pageSizeStash = pageSizeStash ? JSON.parse(pageSizeStash) : {};
    if(pageSizeStash.hasOwnProperty('user')){
      this.params['pageSize'] = pageSizeStash.user;
    }
    if(pageSizeStash.hasOwnProperty('dept')){
      this.subDepartmentsPage['pageSize'] = pageSizeStash.dept;
    } 
    this.buildColumn();
    this.initialize();
    this.getUserTag()
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$eventBus.$on('submit', this.userAdd)
  },
  methods: {
    openChangeDialog(row){
      console.log(row)
      this.currentRow = row
      this.$refs.changeDialog.openDialog()
    },
    toExport(){
      // this.$platform.openTab({
      //   id: 'M_ORG',
      //   title: '组织架构',
      //   url: '/security/department'
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityDepartment,
      })
    },
    getUserTag(){
      serviceProviderApi.userTag().then(r=>{
        if(r.status == 0)
          this.isDelete = r.data
      })
    },
    userDialogSubmit() {
      this.$refs.createUserPanel.validate();
    },
    getCol() {
      if (this.getStroge()) {
        this.columnsList = JSON.parse(this.getStroge());
      } else {
        this.columnsList = this.columns();
      }
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    async saveColumnStatus(event) {
      let columns = event.data || [];
      localStorage.setItem('serviceProvider', JSON.stringify(columns));
      this.$message.success(this.$t('common.base.saveSuccess'));
      this.getCol();
    },
    getStroge() {
      return localStorage.getItem('serviceProvider') || null;
    },
    changeCol() {
      // window.TDAPP.onEvent('pc：服务商管理-选择列事件');
      this.$refs.advanced.open(this.columnsList);
    },
    columns() {
      return [
        {
          label: '服务商名称',
          displayName: '服务商名称',
          fieldName: 'serviceProviderName',
          field: 'serviceProviderName',
          show: true,
          fixed: true,
          isSystem: true,
          tableName: 'serviceProvider',
          width:'150px'
        },
        {
          label: '社会统一信用代码',
          displayName: '社会统一信用代码',
          fieldName: 'creditCode',
          field: 'creditCode',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true,
          width:'200px'
        },
        {
          label: '服务商属性',
          displayName: '服务商属性',
          fieldName: 'serviceProviderAttribute',
          field: 'serviceProviderAttribute',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true,
          width:'200px'
        },
        {
          value: 'registerCompanyName',
          label: '注册公司名称',
          displayName: '注册公司名称',
          fieldName: 'registerCompanyName',
          field: 'registerCompanyName',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true,
          width:'200px'
        },
        {
          value: 'serviceProviderManager',
          label: '服务商主管',
          displayName: '服务商主管',
          fieldName: 'serviceProviderManager',
          field: 'serviceProviderManager',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true,
          width:'180px'
        },
        {
          value: 'serviceProviderContact',
          label: '联系人',
          displayName: '联系人',
          fieldName: 'serviceProviderContact',
          field: 'serviceProviderContact',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'linkPhone',
          label: '电话',
          displayName: '电话',
          fieldName: 'linkPhone',
          field: 'linkPhone',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'wechat',
          label: '微信',
          displayName: '微信',
          fieldName: 'wechat',
          field: 'wechat',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'email',
          label: '邮箱',
          displayName: '邮箱',
          fieldName: 'email',
          field: 'email',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'legalPerson',
          label: '法人代表',
          displayName: '法人代表',
          fieldName: 'legalPerson',
          field: 'legalPerson',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'address',
          label: '注册地址',
          displayName: '注册地址',
          fieldName: 'address',
          field: 'address',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'tagPlaceList',
          label: '负责区域',
          displayName: '负责区域',
          fieldName: 'tagPlaceList',
          field: 'tagPlaceList',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        },
        {
          value: 'label',
          label: '标签',
          displayName: '标签',
          fieldName: 'label',
          field: 'label',
          tableName: 'serviceProvider',
          isSystem: true,
          fixed: true,
          show: true
        }
      ];
    },
    addAdmin(id) {
      // this.$platform.openTab({
      //   id: 'serviceProviderView_home',
      //   title: '服务商主页',
      //   close: true,
      //   url: `/security/tag/serviceProviderHome/${id}?parentTab=${this.currentTabId}`
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceProviderViewHome,
        key: id,
        params: `parentTab=${this.currentTabId}`,
      })
    },
    ChildTagList(name) {
      if (name) {
        this.subDepartmentsPage.keyword = name;
      } else {
        delete this.subDepartmentsPage.keyword;
      }
      if (!this.subDepartmentsPage.pageSize) {
        this.subDepartmentsPage.pageSize = 10;
      }
      if (this.subDepartmentsPage.pageNum == 1) {
        this.subDepartmentsPage.list = [];
      }
      this.subDepartmentsPage.parentId = this.selectedDept.id;
      let res = serviceProviderApi.list(this.subDepartmentsPage);
      return res.then(deptList => {
        this.loading = false
        this.subDepartmentsPage.merge(Page.as(deptList.data));
      });
    },
    submit() {
      this.$refs.team.submit(params => {
        if (!params.parentId) {
          params.parentId = this.selectedDept.id;
          serviceProviderApi.create(params).then(r => {
            this.$platform.notification({
              title: !r.status ? '成功' : '失败',
              message: !r.status ? '创建成功' : r.message,
              type: !r.status ? 'success' : 'error'
            });
            this.submitAddDept();
          });
        } else {
          serviceProviderApi.edit(params).then(r => {
            this.$platform.notification({
              title: !r.status ? '成功' : '失败',
              message: !r.status ? '修改成功' : r.message,
              type: !r.status ? 'success' : 'error'
            });
            this.submitAddDept();

            // 更新主页内容
            this.$platform.refreshTab('serviceProviderView_home');
          });
        }
      });
    },
    submitAddDept() {
      this.deptDialogVisible = false;
      this.initialize(false);
    },

    /* 打开服务电话弹出框 */
    openTelDialog() {
      this.$refs.serviceTelModal.open();
    },
    openWxDialog() {
      this.$refs.serviceWxModal.open();
    },
    subDeptSearch: _.debounce(function(e) {
      // 下级服务商模糊搜索
      this.subDepartmentsPage.pageNum = 1;
      this.subDepartmentsPage.pageSize = 10;
      this.ChildTagList(e);
    }, 500),

    /* 批量更新 */
    openUpdateModal(){
      this.$refs.updateModal.open();
    },
    btnCollapse(dir) {
      if (dir === 'left') {
        this.collapse = true;
        this.collapseLeft = !this.collapseLeft;
        this.collapseRight = true;
      } else {
        this.collapse = false;
        this.collapseRight = !this.collapseRight;
        this.collapseLeft = true;
      }
    },
    debounce: _.debounce(async function() {
      this.isSearchDepts = true;
      // 服务商模糊搜索
      try {
        this.depts = await this.fetchDept();
        if(this.depts[0]) this.initDeptUser(this.depts[0]);
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    }, 1000),
    toggleEnable(row) {
      row.pending = true;
      this.$http
        .post('/security/user/enable', { userId: row.userId }, false)
        .then(res => {
          row.pending = false;
          if (res.status) return this.$platform.alert(res.message);
          this.initialize(false);
        })
        .catch(err => {
          row.pending = false;
          console.error('toggleStatus catch err', err);
        });
    },
    async deleteDeptUser(row) {
      if (
        await this.$platform.confirm(
          '确定要把选中成员删除吗？删除后将清空账号的角色信息'
        )
      ) {
        row.pending = true;
        this.$http
          .post('/security/user/delete', { userId: row.userId }, false)
          .then(res => {
            row.pending = false;
            if (res.status) return this.$platform.alert(res.message);
            this.initialize(false);
          })
          .catch(err => {
            row.pending = false;
            console.error('toggleStatus catch err', err);
          });
      }
    },

    // 导出动态
    exportFeed(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      this.exportDialogvisible = true;
    },
    // 导出账号
    exportAccount(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      if (export_state === 'all') {
        // 导出全部
        window.location.href = !this.selectedDept.parentId
          ? '/security/user/tag/exportBatch?type=1'
          : `/security/user/tag/exportBatch?tagId=${this.selectedDept.id}&type=1`;
      } else {
        // 导出选中的
        let ids = [];
        for (const user of this.multipleSelection) {
          ids.push(user.userId);
        }
        // ids = ids.join(',');
        const params = {
          userIdList : ids
        }
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post('/security/user/tag/exportBatch/new', params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
        // window.location.href = `/security/user/tag/exportBatch?userIdsStr=${ids}&type=1`;
      }
      export_state = '';
    },
    exportData() {
      let api = this.activeTypes.length > 0 ? '/security/user/taskRecord/exportBatch' : '/security/user/workState/exportBatch/new'
      let types = this.activeTypes.join(',');
      const [timeStart = '', timeEnd = ''] = this.selectdatetime || []
      const params = {
        timeStart,
        timeEnd,
        searchByTypesStr: types,
      }
      objectDateToTimestamp(params, ['timeStart', 'timeEnd'])

      if (export_state === 'all') {
        // 导出全部
        params.tagId = this.selectedDept?.id
        window.location.href = `${api}?${objectToUrlParams(params)}`
      } else {
        // 导出选中的
        params.userIdsStr = (this.multipleSelection || []).map(item => item.userId).join(',')
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post(api, params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
      }
      export_state = '';
      this.selectionToggle();
      this.exportDialogClosed();
    },
    exportDialogClosed() {
      this.selectdatetime = '';
      this.exportDialogvisible = false;
    },
    userResetPwdConfirm(userId) {
      this.resetDialogvisible = true;
      this.resetForm.userId = userId;
    },
    resetDialogClosed() {
      this.resetForm.userId = '';
      this.resetForm.pwd = '';
      this.resetDialogvisible = false;
    },

    async resume(userId) {
      try {
        if (await this.$platform.confirm('确定要恢复该账号吗？')) {
          const { status, message } = await http.post(
            '/security/user/resume',
            { userId },
            false
          );
          // if(status !== 0) this.$message.error(message || '');
          let isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '账号恢复成功' : message,
            type: isSucc ? 'success' : 'error'
          });
          isSucc && this.chooseRole(this.selectedRole);
        }
      } catch (error) {
        console.error(error);
      }
    },
    createTransTab(type, userId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'M_JOBTRANSFER_DETAIL',
      //   title: '转交详情',
      //   close: true,
      //   url: `/jobtransfer/view?type=${type}&userId=${userId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageJobtransferView,
        params: `type=${type}&userId=${userId}`,
        fromId
      })
    },
    async resetUserPwd() {
      const isValidate = await this.$refs.restFormRef.validate();
      if (!isValidate) return;

      let params = {};
      params.userId = this.resetForm.userId;
      params.password = md5(this.resetForm.pwd);
      resetPwdUpdateAdmin(params)
        .then(result => {
          let isSucc = result.status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '密码重置成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
          if (isSucc) this.resetDialogClosed();
        })
        .catch(err => console.log(err));
    },

    search() {
      // 组织架构人员搜索
      this.initDeptUser(this.selectedDept);
    },
    searchRole() {
      // 角色人员搜索
      this.rolePage.list = [];
      this.chooseRole(this.selectedRole);
    },
    chooseDelRole() {
      this.activeName = 'role';
      this.selectedDept = {};
      this.rolePage.list = [];
      let role = { id: -1, text: '已删除账号' };
      this.chooseRole(role);
    },
    async chooseRole(role) {
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.selectedRole.id != role.id) {
        this.roleKeyword = '';
      }
      this.selectedRole = role;
      this.roleLoading = true;
      // 获取角色下面的人员
      this.roleParams.keyword = this.roleKeyword;
      this.roleParams.roleId = '';
      this.roleParams.roleType = '';
      this.roleParams.pageNum = 1;
      this.roleParams.type = 1
      this.rolePage.list = [];
      if (role.id == 0) {
        // 待分配账号
        this.roleParams.roleType = 'noauth';
        this.getBuyAndUseUserNumData(); // 已开通账号数量
      } else if (role.id == -1) {
        // 已删除账号
        this.roleParams.roleType = 'delauth';
      } else {
        this.roleParams.roleId = role.id;
      }
      return this.getRoleUserList(this.roleParams)
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },

    getRoleUserList(params) {
      if (this.selectedRole.id == -1) return getDelUser(params);
      return getRoleUser(params);
    },
    getBuyAndUseUserNumData() {
      getBuyAndUseUserNum()
        .then(result => {
          let data = result.data || {};
          this.userCount = data.userCount || 0; // 已开通账号数量
          this.accountNum = data.accountNum || 0; // 账号总数量
          this.surplusNum = Number(data.accountNum) - Number(data.userCount) || 0;
        })
        .catch(err => console.log(err));
    },
    handleClick(tab, event) {
      if (tab.name === 'role') {
        this.chooseRole(this.selectedRole);
      }
    },
    async handleClick1(tab, event) {
      this.loading = true;
      if (tab.name === 'user') {
        this.params.pageNum = 1;
        // 请求成员信息
        await this.fetchUser();
      } else {
        // 请求下级服务商信息
        await this.ChildTagList();
      }
      this.loading = false;
      this.$nextTick(()=> {
        this.knowTableContainerHeight()
      })
    },
    addDepartment(br) {
      if (br) {
        this.showParent = true;
      } else {
        this.showParent = false;
      }
      this.deptEditId = 0;
      this.deptDialogVisible = true;
    },
    async delDepartment(id) {
      // 您删除的团队，如果包含子团队将会一并删除，是否继续？
      try {
        const isChildren = this.selectedDept.children?.length > 0;
        if (
          await this.$platform.confirm(
            isChildren ? '您删除的部门，如果有子部门，也将一并删除，是否继续删除?'
              : '服务商删除后，服务商下的账号将会在外部服务商下显示；为保证账号的正常使用，请尽快分配新的部门'
          )
        ) {
          let ids = [this.selectedDept.serviceProviderTenantId];
          if (id) ids = [id];

          let result = await serviceProviderApi.serviceProviderDelete(ids);

          this.$platform.notification({
            type: result.status == 0 ? 'success' : 'error',
            title: `服务商删除${result.status == 0 ? '成功' : '失败'}`,
            message: result.status == 0 ? null : result.message
          });

          if (result.status == 0) {
            this.initialize(true);
          }
        }
      } catch (e) {
        console.error('teamDelete catch error', e);
      }
    },

    /** 选择服务商 */
    chooseDept(event) {
      console.log('chooseDept event');
      let { node, value } = event;
    },
    chooseUser(type) {
      let options = {
        title: '请选择成员',
        seeAllOrg: true,
        max: -1,
        selectedUsers: this.userPage.list,
        mountEl: this.$el,
        typeServiceProvider: 1
      };
      
      /** 
       * FIXME: 选人组件
      */
      this.$fast.select.multi.user(options)
        .then(result => {
          // console.log(result);
          if (result.status == 0) {
            let data = result.data || {};
            if (data.users.length) {
              this.addUserForm.userIds = data.users.map(r => r.userId);
              this.changeRoleSubmit();
            }
          }
        })
        .catch(err => console.error(err));
    },
    changeRoleSubmit() {
      this.addUserForm.tagIds = [this.selectedDept.id];
      serviceProviderApi.bindUser(this.addUserForm).then(r => {
        this.$platform.notification({
          title: r.status === 0 ? '分配成功' : '分配失败',
          message: r.status === 0 ? '分配成功' : r.message,
          type: r.status === 0 ? 'success' : 'error'
        });
        if(r.status !== 0) return;

        this.addUserForm.isChangeRole = false;
        this.initialize(false);
      });
    },
    /** 抓取服务商数据 */
    fetchDept() {
      let params = {
        seeAllOrg: this.isSeeAllOrg,
        keyword: this.deptKeyword
      };

      return serviceProviderApi
        .tree(params)
        .then(result => {
          return (result && result.data) || [];
        })
        .catch(err => console.error('err', err));
    },
    /* 抓取服务商 人员数量 */
    fetchDeptCount() {
      return getDepartmentUserCount();
    },
    /** 抓取用户数据 */
    fetchUser() {
      let params = this.params;
      if (params.pageNum == 1) {
        this.userPage.list = [];
      }
      params.tagId = this.selectedDept.serviceProviderTenantId || this.selectedDept.parentId ? this.selectedDept.id : '';
      params.type = this.selectedDept.type || '';

      return TeamApi.userList({
        ...params,
        ...this.buildSearchParams()
      })
        .then(userPage => {
          
          this.userPage.merge(Page.as(userPage));
        })
        .catch(err => console.error('err', err));
    },
    /* 查询是否开启 降低组织架构的开关 */
    getSeeAllOrg() {
      return http.post('/setting/user/getSeeAllOrg').then(result => {
        return result;
      });
    },
    /* 跳转 用户详情页 */
    goUserDetail(id) {
      if (!window.frameElement) return;

      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `tab_department_view_${id}`,
      //   title: '成员详情',
      //   close: true,
      //   reload: true,
      //   url: `/security/user/view/${id}?from=department`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: id,
        params: 'from=department',
        reload: true,
        fromId
      })
    },

    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageNum = 1;

      this.userPage.list = [];

      this.loading = true;
      let stash_data = storageGet(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSet(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))

      this.fetchUser().finally(() => (this.loading = false));
    },
    depthandleSizeChange(pageSize) {
      this.subDepartmentsPage.pageSize = pageSize;
      this.subDepartmentsPage.pageNum = 1;
      this.subDepartmentsPage.list = [];
      this.loading = true;
      let stash_data = storageGet(pageSizeStorageKey) || '';
      stash_data = stash_data ? JSON.parse(stash_data) : {};
      storageSet(pageSizeStorageKey, JSON.stringify({ ...stash_data,
        [this.activeName1]:pageSize
      }))
      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleHandleSizeChange(pageSize) {
      this.roleParams.pageSize = pageSize;
      this.roleParams.pageNum = 1;

      this.rolePage.list = [];

      this.roleLoading = true;

      // this.fetchUser().finally(() => this.loading = false);
      return this.getRoleUserList({...this.roleParams, ...this.buildSearchParams()})
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    /** 初始化 */
    initialize(isInit = true) {
      this.initializeDept(isInit);
    },
    /** 初始化服务商数据 */
    async initializeDept(isInit = true) {
      this.loading = true;
      this.isSeeAllOrg = false;

      try {
        /* 如果开启 查询按组织架构选项 */
        let result = await this.getSeeAllOrg();
        this.isSeeAllOrg = result.data;
      } catch (error) {
        console.log('error: ', error);
      }

      let subtask = [this.fetchDept(), this.fetchDeptCount()];

      Promise.all(subtask)
        .then(result => {
          let depts = result[0] || [];
          let deptUserCount = result[1] || {};

          this.deptUserCount = deptUserCount.data || {};
          if(depts && depts.length > 0 && !depts[0].children){
            depts[0].children = [];
          }
          this.depts = depts;
          this.initDeptUser(
            isInit ? this.depts[0] : _.cloneDeep(this.selectedDept)
          );

          this.$nextTick(()=> {
            if(isInit) {
              this.treeHeight =
                  ((this.$refs?.addbtnRef?.$el?.offsetHeight + 14) || 0) + // 添加外部服务商按钮的高度加margin边距14
                  ((this.$refs?.searchbtnRef?.offsetHeight + 10) || 0) + // 输入框的高度加margin边距10
                  (this.$refs?.deleteBtnRef?.offsetHeight || 0); // 删除按钮的高度
            }
            this.knowTableContainerHeight()
            let that_ = this;
            window.onresize = _.debounce(()=>{
              that_.knowTableContainerHeight()
            }, 500)
          })
        })
        .catch(err => console.error(err));
    },
    /** 选中一个服务商 */
    async initDeptUser(dept) {
      this.loading = true
      this.subDeptKeyword = '';
      this.activeName = 'tag';
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.activeName == 'tag' && this.selectedRole.id == -1) {
        this.selectedRole = { id: '0', text: '待分配人员' };
      }
      try {
        if (this.selectedDept.serviceProviderId != dept.serviceProviderId) {
          this.keyword = '';
        }
        this.selectedDept = dept;
        this.subDepartmentsPage.pageNum = 1;
        this.userPage.list = [];
        // 查询用户
        this.params.keyword = this.keyword;
        // 只有选择的不是主tag 搜索人员就不传tagid 后端返回主tag的parentId为null
        if (dept.parentId) {
          this.params.id = dept.serviceProviderId || dept.serviceProviderId;
        } else {
          this.params.id = '';
        }
        // this.params.departmentId = dept.id;
        this.params.pageNum = 1;
        this.params.seeAllOrg = this.isSeeAllOrg;
        this.fetchTeamData();
        await this.handleClick1({ name: this.activeName1 });
      } catch (error) {
        console.error(error);
        this.loading = false;
      }

    },
    // 查询详情
    async fetchTeamData() {
      if (!this.selectedDept.serviceProviderId && !this.selectedDept.serviceProviderTenantId) return;
      try {
        let result = await serviceProviderApi.info({
          id: this.selectedDept.serviceProviderId || this.selectedDept.serviceProviderTenantId
        });
        if (result.status) {
          this.deptInfo = {};
          return this.$platform.notification({
            title: '失败',
            message: result.message,
            type: 'error'
          });
        }
        if (result.data) {
          this.deptInfo = result.data;
          this.subDepartments = this.deptInfo.children || [];
        }

        // this.subDepartments.merge(Page.as(result));
      } catch (error) {
        console.log('error: ', error);
      }
    },
    isRootDepartment(department = {}) {
      return this.depts.some(dept => dept.id == department.id);
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;

      this.userPage.list = [];

      this.loading = true;

      this.fetchUser().finally(() => (this.loading = false));
    },
    deptjump(pageNum) {
      this.subDepartmentsPage.pageNum = pageNum;
      this.subDepartmentsPage.list = [];
      this.loading = true;

      this.ChildTagList().finally(() => (this.loading = false));
    },
    roleJump(pageNum) {
      this.roleParams.pageNum = pageNum;

      this.rolePage.list = [];

      this.roleLoading = true;

      return this.getRoleUserList({...this.roleParams, ...this.buildSearchParams()})
        .then(rolePage => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch(err => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },
    nodeRender(h, node) {
      let content = (
        <span>
          {node.tagName}（{node.userCount || 0}）
        </span>
      );

      let count = this.deptUserCount[node.id] || 0;
      if (count <= 0) return content;

      return (
        <div class="dept-node-wrap">
          <span class="dept-node-name">{node.tagName}</span>
          <span class="dept-node-count">&nbsp;({count})人</span>
        </div>
      );
    },
    openCreateUserPanel(row) {
      if (row) {
        let obj = JSON.parse(JSON.stringify(row));
        obj.dateTime = safeNewDate().getTime();
        this.userRow = row ? JSON.stringify(obj) : '';
      }else{
        this.userRow = ''

        setTimeout(()=>{
          this.$refs.createUserPanel.form.tagList = [this.selectedDept];
        }, 0)
      }
      this.userDialogVisible = true;
      // this.$refs.createUserPanel.open({});
    },
    openDepartmentEditPanel(id) {
      this.deptEditId = id
      this.showParent = false;
      this.deptDialogVisible = true;
      this.$refs.team.initKeyVal();
    },
    /** select dept person */
    selectionHandle(selection) {
      this.multipleSelection = selection.slice();
    },
    selectionToggle(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    /** select role person */
    roleSelectionHandle(selection) {
      this.roleMultipleSelection = selection.slice();
    },

    async userDeleteConfirm(type) {
      // 批量删除
      if (type === 'multiple' && this.multipleSelection.length <= 0) {
        return this.$platform.alert('请先选择需要移除的成员');
      }

      if (
        await this.$platform.confirm('确定要把选中成员从该服务商中移除吗？')
      ) {
        this.userDelete();
      }
    },
    userDelete() {
      let params = {
        userIds: this.multipleSelection.map(item => item.userId).join(','),
        tagId: this.selectedDept.id
      };

      this.loading = true;

      TeamApi.deleteUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.initialize(false);
            if(!this.deptDialogVisible) this.deptEditId = '';
          }

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '移除成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    userAdd(form = {}) {
      let params = JSON.parse(JSON.stringify(form));
      if(!params.userId)
        params.loginPassword = md5(params.pass);
      params.roles = params.role.map(r => ({ id: r })) || [];

      this.loading = true;

      createAndAddDepartmentUser(params)
        .then(result => {
          let isSucc = result.status == 0;

          if (isSucc) {
            this.userDialogVisible = false;
            // this.$refs.createUserPanel.close();
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '添加成功' : result.message,
            type: isSucc ? 'success' : 'error'
          });
        })
        .catch(err => console.log(err))
        .finally(() => (this.loading = false));
    },
    // 帮助文档
    openHelpDoc() {
      let url = ''
      if(this.tenantType == 2) {
        url = 'https://docs.qq.com/doc/p/2cec0fde98fc3e19274e129ae3806db7de08a065?dver=2.1.27237808'
      } else if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnUYQrZg1Kc1d0L9TB1Shjz3'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/br34li8lnnceroyp/yugh4uyttozl4210.html'
      }
      platform.openLink(url);
    },
    // 构建搜索参数
    buildSearchParams() {
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      
      const {tags, roleIds, enabled, labelIds} = advancedSearchParams;
      const tagIdsStr = tags?.map(x=>x.id);
      
      return {
        ...this.params,
        roleIds: roleIds?.filter(x=>x !== RoleType)?.join(','),
        tagIds: tagIdsStr?.filter(x=>x !== TagType)?.join(','),
        enabled: enabled ? Number(enabled) : '',
        labelIds: labelIds?.join(','),
        advancedSearchRoleType: roleIds?.some(x=>x === RoleType),
        advancedSearchTagType: tagIdsStr?.some(x=>x === TagType)
      }
    },
    // 高级搜索
    panelSearchAdvancedToggle() {
      this.getRoleListData();
      this.getBaseLabelList();
      this.visible = true;
    },
    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // 重置
    resetParams() {
      window.location.reload()
    },
    // 获取角色列表
    getRoleListData(){
      serviceProviderApi.getRoleTree()
        .then( result => {
          if(!result || !result.data || !result.data.children || result.data.children.length < 2)
            return false
          
          if(result.data.children[1].type === 'assigned'){
            let roles = result.data.children[1].children;
            this.rolesList = roles.map(role => ({ text: role.roleName, value: role.roleId }));
            this.rolesList.unshift({ text: '无', value: RoleType })
          }
        })
        .catch((err) => console.error(err));
    },
    // 获取标签数据
    getBaseLabelList(){
      getBaseLabelList().then(res=>{
        const { status, data, message } = res;
        if(status !== 0) return;

        this.baseLaberlList = data.map(x=>({text: x.tagName, value: x.id}));
      })
    },
    // 添加服务商成员按钮
    async addServiceMember(flag){
      if(!flag && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');

      this.addMemberVisible = true;
      this.addMemberFlag = flag;
    },
    // 添加操作
    addMemberSubmit(){
      if(this.addMemberFlag){
        this.$refs.serviceAddForm.addMemberSubmit();
      }else {
        const ids = this.multipleSelection.map(x => x.userId);
        this.$refs.serviceAddForm.addMemberSubmit(ids);
      }
    },
    // 提交成功
    succSubmit(){
      this.addMemberVisible = false;

      this.initialize();
      this.getRoleListData();
    },

    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let stash_data = storageGet('notStandardTableStash') || '';
      stash_data = (stash_data && JSON.parse(stash_data)) || {};
      if(this.activeName1 == 'dept'){
        let baseList = _.cloneDeep(this.columnsList)
        baseList = baseList.map(i => ({field:i.field, width:i.field == column.property ? `${column.width}px` : i.width || ''})).reduce((acc, col) => (acc[col.field] = col) && acc, {});
        stash_data[`${this.tableStashKey}${this.activeName1}`] = baseList
      }else {
        this.$set(this.tableListForWidthStash, column.property, {width:`${column.width}px`});
        stash_data[`${this.tableStashKey}${this.activeName1}`] = this.tableListForWidthStash
      }
      
      storageSet('notStandardTableStash', JSON.stringify(stash_data));
    },
    /**
     * @des 初始化表格宽度函数
     */
    buildColumn(){
      try {
        let stash_data = storageGet('notStandardTableStash');
        stash_data = stash_data && JSON.parse(stash_data);
        let pageStash = stash_data[`${this.tableStashKey}${this.activeName1}`] || {};
        if(this.activeName1 == 'dept'){
          this.columnsList.map(item=>{
            if(pageStash.hasOwnProperty(item.field)){
              item['width'] = pageStash[item.field].width
            }
            return item
          })
        }else {
          this.$set(this, 'tableListForWidthStash', {...this.tableListForWidthStash, ...pageStash});
        }
        
      } catch (error) {
        console.warn(error, 'error try catch');
      }

    },
    async actionMany(type){
      if (this.multipleSelection.length <= 0) {
        return this.$platform.alert(`请先选择需要${ type == 'enable' ? '启用' : '禁用' }的成员`);
      }
      if (await this.$platform.confirm(`确定要把选中成员全部${ type == 'enable' ? '启用' : '禁用' }吗？`)) {
        this.userEnable(type);
      }
    },
    userEnable(type){
      let params = this.multipleSelection.map(item => item.userId)
      if(type == 'enable'){

        TeamApi.enableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? '成功' : '失败',
              message: isSucc ? '批量启用成功' : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }else{
        TeamApi.unableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? '成功' : '失败',
              message: isSucc ? '批量禁用成功' : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }
    },
    updateSuccess(){
      this.$refs.multipleTable.clearSelection();
      this.roleMultipleSelection = [];
    },
    // 下载批量更新模板
    downloadTem(){
      if (!this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
      let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
      let url = '/security/user/updateTemplateExport/new';
      let userIdsStr = [];
      for (const user of this.multipleSelection) {
        userIdsStr.push(user.userId);
      }
      // userIdsStr = userIdsStr.join(',');
      let params = {
        userIdList: userIdsStr,
        // type:1
      }
      this.$http.post(url, params, true, {responseType: 'blob'})
        .then(blob => {
          let link = document.createElement('a');
          let url = URL.createObjectURL(blob);
          link.download = fileName;
          link.href = url;
          this.$refs.bridge.appendChild(link);
          link.click();
          setTimeout(() => {
            URL.revokeObjectURL(url);
            this.$refs.bridge.removeChild(link);
          }, 150);
        })
        .catch(err => console.error(err));
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      let delMin = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        delMin =  window_ - 20 - 64 - 56;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 20 - 40 - 66 - 56 ;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
        delMin = delMin > 440 ? delMin : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'delTableContainerHeight', `${delMin}px`)
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
  },
  components: {
    [CreateUserPanel.name]: CreateUserPanel,
    [TeamEditView.name]: TeamEditView,
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [ServiceAddMember.name]: ServiceAddMember,
    [ChangeDialog.name]: ChangeDialog,
  }
};
</script>

<style lang="scss">
.disable-popover, .transfer-btn {
  margin-left: 12px;
}
.disable-text {
  cursor: not-allowed;
  color: #c0c4cc !important;
}
.no-data-block {
  line-height: 30px;
  margin-top: 10px;
  text-align: center;
  color: #595959;
   font-size: 14px;
   padding-bottom:12px;
  .service-no-icon{
  display: block;
  height: 134px;
  margin: 32px auto 16px;
}
}

.el-form-item--small.el-form-item{
  margin-bottom: 16px;
}
.department-detail-header-title-box.department-detail-header-title span{
  margin-right:0;
  font-weight: normal;
}
.add-dialog-container.service_body{
  padding:10px;
  z-index:2000;
  .el-form.demo-ruleForm{
    width: 98%;
    overflow:hidden;
    padding-top:10px
  }
  .base-modal.transition__container{
    max-height: calc(100% - 120px);
    max-height: calc(100vh - 120px);
  }
}
.dialog_body{
  .el-dialog__body{
    height: 500px;
    overflow-y: auto;
  }
}
.el-tabs__header {
  margin-left: -1px;
      margin: 0;
}
.el-tabs__content {
  min-width: 300px;
}

.collapse {
  span {
    padding: 5px;
    cursor: pointer;
    color: #666;
  }
  div{
    height: 53px;
    border-top: none;
    i.iconfont.icon-mianbanjiantou{
      font-size:18px;
    }
  }
}

.el-tabs-expand {
  width: 400px;
}

</style>
<style lang="scss">
  @import "./serviceProviderView.scss";
</style>
<style lang="scss" scoped>
.department-detail-header-title{
  margin-bottom: 12px;
  font-size: 16px;
}
.department-container {
  ::v-deep .v-step[data-v-7c9c03f0] {
    background: #fff !important;
    color: #333 !important;
    -webkit-filter: drop-shadow(
      0px 9px 28px 8px rgba(0, 0, 0, 0.05)
    ) !important;
    filter: drop-shadow(0px 9px 28px 8px rgba(0, 0, 0, 0.05)) !important;
    padding: 0 !important;
    min-width: 240px !important;
    max-width: 350px !important;
  }

  ::v-deep .v-step .v-step__arrow[data-v-7c9c03f0] {
    border-color: #fff;
    border-left-color: transparent !important;
    border-right-color: transparent !important;
  }

  .tour-content-box {
    position: relative;
    overflow: hidden;
    padding: 0 20px;
    border-radius: 4px;

    .tour-left-tips {
      width: 80px;
      height: 32px;
      background: $color-primary;
      color: #fff;
      position: absolute;
      left: -40px;
      top: 0px;
      line-height: 40px;
      font-size: 12px;
      transform-origin: center top;
      transform: rotateZ(-45deg);
      text-align: center;
    }

    .tour-content {
      .tour-content-head {
        padding-top: 32px;
        padding-bottom: 10px;

        .iconfont {
          font-size: 10px;
          margin-bottom: 2px;
          color: #999;
          cursor: pointer;
        }
      }

      .tour-content-con {
        text-align: start;
        padding-bottom: 12px;
        color: #666;
      }
    }
  }

  .tour-bottom {
    height: 52px;
    padding: 0 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btns {
      width: 60px;
      height: 28px;
      background: $color-primary;
      color: #fff;
      text-align: center;
      line-height: 28px;
      border-radius: 4px;
    }

    .text {
      color: $color-primary;
    }

    :nth-child(n) {
      cursor: pointer;
    }

    :not(:last-child) {
      margin-right: 12px;
    }
  }

  /* 向上的箭头 */

  .normal-arrow-top {
    font-size: 0;
    line-height: 0;
    border-width: 0.5rem;
    border-color: #fff;
    width: 0;
    border-top-width: 0;
    border-style: dashed;
    border-bottom-style: solid;
    border-left-color: transparent;
    border-right-color: transparent;
    position: absolute;
    top: -0.5rem;
  }

  .guide-model-box {
    position: fixed;
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 996;
  }

  .guide-point {
    z-index: 997;
    position: sticky;
  }

  .bg-w {
    background: #fff;
  }

  .dept-step-1-box {
    position: absolute;
    top: 0;
    z-index: 997;
  }
}
.form-view-row-content-address {
  cursor: pointer;
}
.form-view-row-content-address:hover {
  color: $color-primary-light-6;
}
.dept-title {
  color: $color-primary-light-6;
  height: 35px;
  box-sizing: border-box;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  margin-top: 10px;
}
.dept-info {
  display: flex;
  padding:6px 0;
  align-items: center;
  .form-view-col{
    display: flex;
    justify-content: flex-start;
    color: #262626;
    padding-right:24px;
    p{
      margin:0;
      line-height:20px
    }
    .form-view-col-content{
      text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    .form-view-col-content-address{
     cursor:auto;
    }
    }
  }
}
.department-empty {
  height: 100%;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 1px 4px rgba(216,216,216,0.65);
  display: -webkit-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  img {
    width: 160px;
  }
  p {
    padding-top: 8px;
    color: $text-color-regular;
  }
}
.export-link {
  color: $color-primary-light-6;
  cursor: pointer;
  text-decoration: underline;
}
.view-detail-btn {
  color: $color-primary;
  cursor: pointer;
}
</style>

<style lang="scss">
.reset-dialog-form-dialog {
  .el-dialog__body {
    padding-bottom: 50px;
  }
}
</style>